package com.xinyuan.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinyuan.entity.Message;
import com.xinyuan.entity.ResultInfo;
import com.xinyuan.service.GetJson;
import com.xinyuan.utils.AmecoUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Classname 统计次数
 * @Description TODO
 * @Date 2020/5/21 17:52
 * @Created by zfl
 */
@WebServlet(name = "UpdateCAMPServlet",urlPatterns = "/updateCAMP")
public class UpdateCAMP extends HttpServlet {
    GetJson json = new GetJson();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决跨域
        response.addHeader("Access-Control-Allow-Origin","*");
        //String filePath = "C:\\Users\\NB_IOT\\Desktop\\test-xlsx.xlsx";
        // 获取ID
        String fileID = request.getParameter("id");
        String filePath = "C:\\upload\\" + fileID + "\\CAMP.xlsx";

        System.out.println("filePath = " + filePath);
        AmecoUtils utils = new AmecoUtils();
        ResultInfo info = new ResultInfo();
        Message message = new Message();
        //注意流之间的互相干扰
        String getJson = utils.acceptJSON(request);
        System.out.println("getJson:" + getJson);
        getJson = utils.ObjectToJson(getJson);
        ObjectMapper mapper = new ObjectMapper();
        info = mapper.readValue(getJson,ResultInfo.class);
        System.out.println("info:" + info);
        //输出ReqJson对象的值
        System.out.println(info.getData());
        response.setContentType("application/json;charset=utf-8");
        if(info.getErrorCode() == 1) {
            message.setMaxInterv(0);
            message.setMinInterv(0);
            message.setData(null);
            message.setErrCode(1);
            message.setMsg("输入错误");
            response.getWriter().write(utils.getJson(message));
        }else {
            //读取文件
            List<String> listCampThreshol = utils.readExcelByRow(filePath, "CAMP_THRESHOL");
            List<Double> listMethod = utils.updateList(listCampThreshol,info.getData().getMethod());
            message =utils.getCount(listMethod,info.getData().getInterval(),info.getData().getBlur());
            response.getWriter().write(utils.getJson(message));
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ResultInfo info = new ResultInfo();
        info.setMsg("200 OK!");
        //响应数据
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        mapper.writeValue(response.getOutputStream(),info);
    }
}
